package gui.resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;

import gen.R;
import gui.Context;
import gui.exception.ImageResourceNotFoundException;

/**
 * 框架资源实现
 * 
 * @author chenj_000
 *
 */
public class GUIResource implements Resource {
	private static final Resource RES = new GUIResource();
	private static final Map<Integer, InputStream> LAYOUT_MAP;
	private static final Map<Integer, ImageIcon> IMAGE_MAP;

	static {
		LAYOUT_MAP = new HashMap<>();
		try {
			for (Field f : R.layout.class.getDeclaredFields()) {
				LAYOUT_MAP.put(f.getInt(null), getResInputStream("layout", f.getName() + ".xml"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		IMAGE_MAP = new HashMap<>();
		try {
			for (Field f : R.image.class.getDeclaredFields()) {
				IMAGE_MAP.put(f.getInt(null), getImage("image", f.getName() + ".png"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private GUIResource() {
	}

	public static Resource getResource() {
		return RES;
	}

	@Override
	public InputStream getConfiguration(String file) {
		File f = new File(Context.getContextPath(), file);
		try {
			return new FileInputStream(f);
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	@Override
	public InputStream getLayout(int layout_id) {
		return LAYOUT_MAP.get(layout_id);
	}

	private static ImageIcon getImage(String dir, String fileName) {
		dir = getResPath() + dir;
		fileName = dir + "/" + fileName;
		return new ImageIcon(fileName);
	}

	private static InputStream getResInputStream(String dir, String fileName) {
		dir = getResPath() + dir;
		File file = new File(dir, fileName);
		try {
			return new FileInputStream(file);
		} catch (Exception e) {
			return null;
		}
	}

	public static String getResPath() {
		return Context.getContextPath() + "/res/";
	}

	@Override
	public ImageIcon getImage(int resId) {
		return IMAGE_MAP.get(resId);
	}

	@Override
	public ImageIcon getImage(String resName) {
		try {
			int id = getResourceID(resName);
			if (id != 0)
				return getImage(id);
			else
				throw new ImageResourceNotFoundException();
		} catch (Exception e) {
			throw new ImageResourceNotFoundException(e);
		}
	}

	@Override
	public int getResourceID(String resource) {
		if (resource == null || resource.trim().length() == 0)
			return 0;
		String dir = resource.substring(resource.indexOf("@") + 1, resource.indexOf("/"));
		String name = resource.substring(resource.indexOf("/") + 1, resource.length());
		try {
			int id = 0;
			Field field;
			field = Class.forName("gen.R$" + dir).getDeclaredField(name);
			id = field.getInt(null);
			return id;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
}
